Skip to content

refactor(append-file)!: redesign rolling file appender with direct segment writes - #250

Merged
tisonkun merged 4 commits into
mainfrom
refactor/rolling-file
Nov 25, 2026
Merged

tisonkun merged 4 commits into
mainfrom
refactor/rolling-file

Conversation

@tisonkun

@tisonkun tisonkun commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

RollingFileWriter previously wrote to an unnumbered active file (app.log) and shifted reverse-numbered archives (.1 -> .2 -> .3) via fs::rename on every rollover. That design performed O(N) metadata and rename syscalls under the writer mutex, risked sharing violations on Windows when external log collectors held open handles without FILE_SHARE_DELETE, opened fresh files without O_APPEND (leaving NUL holes under external copytruncate), panicked on prefix/suffix boundary matches or extreme timestamps, truncated epoch milliseconds to usize on 32-bit targets, and juggled nested Error wrappers and intermediate Option<Error> values across rollover and cleanup paths.

This PR redesigns logforth-append-file around direct segment writes and straight-line, single-layer error propagation, and splits historical (<= 0.30.1) release notes into CHANGELOG-OLD.md while aligning CHANGELOG.md under ## Unreleased.

Rollover and Filename Layout Changes

With FileBuilder::new(dir, "app").filename_suffix("log"):

Policy Previous (0.4.0) New
No rotation app.log app.log (unchanged)
Daily Active app.log; rotated app.2026-11-25.1.log, .2.log (newest = 1) Direct write to app.2026-11-25.log
Size Active app.log; rotated app.1.log, app.2.log (newest = 1) Direct write to app.1.log, app.2.log, ... (oldest = 1, newest = highest)
Hourly and size Active app.log; rotated app.2026-11-25-17.1.log, .2.log (newest = 1) Direct write to app.2026-11-25-17.1.log, .2.log, ... (oldest = 1, newest = highest)

Concrete rollover and retention behavior when rollover_size and max_log_files are configured:

given:
filename = app
filename_suffix = log
rollover_size = 10 MiB
max_log_files = 3

before 4th segment rollover (3 matching files retained, active = app.3.log):
app.1.log   (oldest, closed)
app.2.log   (closed)
app.3.log   (active)

on next write that would exceed 10 MiB:
app.2.log   (oldest retained)
app.3.log   (closed, never renamed)
app.4.log   (new active segment)
- app.1.log deleted

Upgrade note for existing log directories: files keep their initial segment name for their entire lifetime instead of being renamed on rollover. Files left behind by the previous layout (such as an unnumbered app.log alongside rotated files, app.<date>.1.log under time-only rotation, or reverse-numbered .1, .2 archives where .1 was newest) are either ignored by the stricter segment parser or ordered by ascending sequence number (1 treated as oldest); move or remove old archives when upgrading in place if strict retention order across versions is required.

API and Behavior Changes

  • FileBuilder::rollover_size now takes NonZeroU64 instead of NonZeroUsize and rotates before a write would exceed max_size (size > 0 && size + len > max_size) rather than after; a single oversized record written to an empty segment occupies that segment whole without extra empty files.
  • Add FileBuilder::timezone(TimeZone) (and pub extern crate jiff) to configure the timezone used for rotation boundaries and period filenames, defaulting to TimeZone::system(). Repeated local hours during DST fall-back reuse the active segment until its second occurrence ends or rollover_size is reached.
  • FileBuilder::max_log_files counts the active file toward the total limit across all periods and never deletes the active file even if the system clock steps backward; startup cleanup runs on a best-effort basis so locked historical files do not fail build().
  • FileBuilder::build validates filename and filename_suffix upfront, returning Err for empty names, . or .., path separators, or NUL bytes, and matches only canonical regular files during retention scans.
  • Open all segment files with .append(true) (O_APPEND), and keep runtime error propagation strictly single-layer: if rollover or retention cleanup fails, set a 1-second wall-clock-safe retry cooldown window, append the current record to the active segment, and return the leaf logforth_core::Error directly.

…gment writes

`RollingFileWriter` previously wrote to a single active file and shifted
reverse-numbered archives (`.1 -> .2 -> .3`) via `fs::rename` on every
rollover. That design performed `O(N)` filesystem renames under the
writer mutex, risked sharing violations on Windows when external log
collectors held open handles, opened new files without `O_APPEND`,
panicked on filename suffix boundary underflows or out-of-range
timestamps, truncated millisecond bounds to `usize` on 32-bit targets,
and juggled multi-layer `Error` wrappers and stashed `Option<Error>`
values across rotation and cleanup paths.

Redesign `logforth-append-file` around direct-write segment files and
flat, single-layer error propagation:

- Write directly to segment files opened with `.append(true)` (`<stem>[.<suffix>]` without rotation, `<stem>.<period>[.<suffix>]` for time rotation, and `<stem>[.<period>].<seq>[.<suffix>]` with ascending `1..` sequence numbers when `rollover_size` is configured), eliminating `fs::rename` completely.
- Check size bounds before writing (`size > 0 && size + len > max_size`) using `NonZeroU64` so segments stay within the configured byte budget while writing oversized single records whole into an empty segment.
- Compute period bounds `[start, end)` in `jiff::Timestamp` across configurable `TimeZone` (`FileBuilder::timezone`, defaulting to the system timezone), reusing the active segment across repeated local hours during DST fall-back and avoiding panics or 32-bit truncation.
- Validate filename stems and suffixes strictly and match only canonical regular segment files during retention cleanup, counting the active file toward `max_log_files` and never unlinking the active segment even if the wall clock steps backward.
- Keep error handling linear and single-layer: if rollover or retention cleanup fails, throttle retries for one second, append the current record to the active segment, and return the underlying leaf `Error` directly.

Signed-off-by: tison <wander4096@gmail.com>
Move historical release notes (`<= 0.30.1`) into `CHANGELOG-OLD.md` and
organize `CHANGELOG.md` under `## Unreleased` using uniform,
caller-facing `Breaking changes`, `New features`, `Improvements`, and
`Bug fixes` entries covering all user-visible changes since `0.30.1`.

Signed-off-by: tison <wander4096@gmail.com>
Standardize crate, type, and method documentation across
`logforth-append-file` with consistent noun-phrase type summaries,
present-tense method contracts, explicit default annotations, structured
`# Errors` conditions on `FileBuilder::build`, and unified crate-level
segment naming and retention sections.

Signed-off-by: tison <wander4096@gmail.com>
…lock tests

Move public-API behavior and regression tests into
`appenders/file/tests/file_test.rs` so input validation, pre-write size
boundaries (including trailing newline framing), retention ordering,
non-matching entry preservation, append-after-truncation, and sequence
exhaustion are exercised end-to-end through `FileBuilder` and `File`.

Keep `src/` unit tests strictly for scenarios requiring private access
(`Clock::ManualClock` in `rolling.rs` and `Rotation::period_at` in
`rotation.rs`), asserting observable file and error outcomes rather than
internal helper predicates.

Signed-off-by: tison <wander4096@gmail.com>
@tisonkun
tisonkun enabled auto-merge (squash) November 25, 2026 13:15
@tisonkun
tisonkun merged commit 8289065 into main Nov 25, 2026
10 checks passed
@tisonkun
tisonkun deleted the refactor/rolling-file branch November 25, 2026 13:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant